<template>
	<div class="check-input-wrapper">
		<div class="page-title">检查结果录入</div>

		<!-- 筛选条件 -->
		<el-card shadow="never" class="filter-card">
			<el-form :inline="true" :model="query" @submit.prevent>
				<el-form-item label="病历号">
					<el-input v-model.trim="query.caseNumber" placeholder="输入病历号" clearable @keyup.enter="loadList" />
				</el-form-item>
				<el-form-item label="姓名">
					<el-input v-model.trim="query.realName" placeholder="输入姓名" clearable @keyup.enter="loadList" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :loading="loadingList" @click="loadList">搜索</el-button>
					<el-button @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- 检查中患者列表 -->
		<el-card shadow="never" class="list-card">
			<template #header>
				<div class="card-header">检查中患者 ({{ requests.length }})</div>
			</template>
			<el-table :data="pagedRequests" size="small" height="320" v-loading="loadingList" @row-click="selectRequest" highlight-current-row>
				<el-table-column type="index" label="#" width="50" />
				<el-table-column prop="patientName" label="姓名" width="110" />
				<el-table-column prop="patientCaseNumber" label="病历号" width="130" />
				<el-table-column prop="patientAge" label="年龄" width="70" />
				<el-table-column prop="patientGender" label="性别" width="70" />
				<el-table-column prop="checkInfo" label="检查信息" min-width="180" show-overflow-tooltip />
				<el-table-column prop="checkEmployeeId" label="检查医生ID" width="110" />
				<el-table-column prop="checkTime" label="检查时间" width="160">
					<template #default="{ row }">{{ formatTime(row.checkTime) }}</template>
				</el-table-column>
				<el-table-column label="选择" width="80">
					<template #default="{ row }">
						<el-button size="small" type="primary" plain @click.stop="selectRequest(row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pager" v-if="requests.length > pageSize">
				<el-pagination layout="prev, pager, next" :page-size="pageSize" :current-page="pageNum" :total="requests.length" @current-change="(p)=>{pageNum=p}" />
			</div>
		</el-card>

		<!-- 录入区 -->
		<el-card shadow="never" class="input-card" v-if="current">
			<template #header>
				<div class="card-header">当前选择的检查申请 #{{ current.id }}</div>
			</template>
			<el-descriptions :column="3" size="small" border class="info-desc">
				<el-descriptions-item label="姓名">{{ current.patientName }}</el-descriptions-item>
				<el-descriptions-item label="病历号">{{ current.patientCaseNumber }}</el-descriptions-item>
				<el-descriptions-item label="年龄/性别">{{ current.patientAge || '-' }}/{{ current.patientGender || '-' }}</el-descriptions-item>
				<el-descriptions-item label="检查信息" :span="3">{{ current.checkInfo }}</el-descriptions-item>
				<el-descriptions-item label="检查部位" :span="3">{{ current.checkPosition || '-' }}</el-descriptions-item>
				<el-descriptions-item label="当前状态">{{ current.checkState }}</el-descriptions-item>
				<el-descriptions-item label="检查医生ID">{{ current.checkEmployeeId || '-' }}</el-descriptions-item>
				<el-descriptions-item label="结果录入医生ID">{{ current.inputcheckEmployeeId || '-' }}</el-descriptions-item>
			</el-descriptions>

			<el-form label-width="110px" class="doctor-form">
				<el-form-item label="结果录入科室">
					<el-select v-model="form.deptId" placeholder="选择科室" filterable style="width:240px" @change="onDeptChange">
						<el-option v-for="d in deptList" :key="d.id" :label="d.deptName || d.dept_name" :value="d.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="结果录入医生">
					<el-select v-model="form.employeeId" placeholder="先选择科室" filterable style="width:240px">
						<el-option v-for="e in doctorList" :key="e.id" :label="e.realName || e.realname" :value="e.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="检查结果">
					<el-input v-model="form.result" type="textarea" :autosize="{minRows:4,maxRows:8}" placeholder="请输入检查结果" />
				</el-form-item>
				<el-form-item>
					<el-space>
						<el-button type="primary" :disabled="!canSubmit" :loading="submitting" @click="handleSubmit">结果提交</el-button>
						<el-button @click="resetForm">重置输入</el-button>
					</el-space>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { listForInput, submitResult } from '@/api/checkRequest'
import request from '@/utils/request'

// 查询条件
const query = reactive({ caseNumber: '', realName: '' })
const loadingList = ref(false)
const requests = ref([])
const pageNum = ref(1)
const pageSize = 8
const current = ref(null)

// 结果录入表单
const form = reactive({ deptId: '', employeeId: '', result: '' })
const deptList = ref([])
const doctorList = ref([])
const submitting = ref(false)

const pagedRequests = computed(()=>{
	const start = (pageNum.value-1)*pageSize
	return requests.value.slice(start, start+pageSize)
})

const canSubmit = computed(()=> !!(current.value && form.employeeId && form.result.trim()))

function formatTime(t){
	if(!t) return '-'
	const d = new Date(t)
	const p = n=> String(n).padStart(2,'0')
	return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
}

async function loadList(){
	loadingList.value = true
	try {
		const resp = await listForInput({ caseNumber: query.caseNumber, realName: query.realName })
		// 拦截器返回统一对象，若使用另一个axios封装请相应调整
		if(resp.data){
			// 若 resp.data 存在说明使用另一封装；兼容两种情况
			requests.value = resp.data
		} else if(Array.isArray(resp)) {
			requests.value = resp
		} else if(Array.isArray(resp.list)) {
			requests.value = resp.list
		} else {
			// 部分封装直接返回数组
			requests.value = Array.isArray(resp) ? resp : []
		}
		pageNum.value = 1
	} catch (e){
		console.error(e)
		ElMessage.error('加载列表失败')
	} finally { loadingList.value = false }
}

function resetQuery(){
	query.caseNumber=''; query.realName=''; loadList()
}

function selectRequest(row){
	current.value = row
	// 重置录入表单
	form.deptId=''; form.employeeId=''; form.result=''; doctorList.value=[]
}

async function loadDeptList(){
	try { const resp = await request.get('/departments'); deptList.value = resp.data || resp.list || resp || [] } catch(e){ console.error(e) }
}

async function loadDoctors(deptId){
	if(!deptId) return
	try { const resp = await request.post('/employees/search', { deptmentId: deptId }); doctorList.value = resp.data || resp.list || resp || [] } catch(e){ console.error(e) }
}

function onDeptChange(val){
	form.employeeId=''; doctorList.value=[]; if(val) loadDoctors(val)
}

async function handleSubmit(){
	if(!canSubmit.value) return
	submitting.value = true
	try {
		const resp = await submitResult(current.value.id, form.employeeId, form.result.trim())
		if(resp.code===200 || resp.success){
			ElMessage.success('结果提交成功')
			// 前端本地更新状态
			current.value.checkResult = form.result.trim()
			current.value.inputcheckEmployeeId = form.employeeId
			current.value.checkState = '已出结果'
			form.result=''
			// 从列表中移除已完成(可选)
			requests.value = requests.value.filter(r=>r.id!==current.value.id)
			current.value = null
		} else {
			ElMessage.error(resp.message || resp.msg || '提交失败')
		}
	} catch(e){ console.error(e); ElMessage.error('提交失败') } finally { submitting.value=false }
}

function resetForm(){
	form.result=''; form.deptId=''; form.employeeId=''; doctorList.value=[]
}

watch(()=>[query.caseNumber, query.realName],()=>{ pageNum.value=1 })

onMounted(()=>{
	loadList(); loadDeptList();
})
</script>

<style scoped>
.check-input-wrapper { padding:16px; display:flex; flex-direction:column; gap:16px; }
.page-title { font-size:22px; font-weight:600; }
.filter-card, .list-card, .input-card { border-radius:12px; }
.card-header { font-weight:600; }
.pager { display:flex; justify-content:flex-end; margin-top:8px; }
.info-desc { margin-bottom:12px; }
.doctor-form { max-width:760px; }
</style>
